package com.paomi.client.activity.pay;

import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.paomi.client.R;
import com.paomi.client.activity.address.ReceivingAddressActivity;
import com.paomi.client.activity.detail.model.DetailTicketBean;
import com.paomi.client.activity.detail.model.EnterTypeBean;
import com.paomi.client.activity.detail.model.PlanBean;
import com.paomi.client.activity.detail.model.PraiseSeatBean;
import com.paomi.client.activity.onlineSeat.model.SeatBean;
import com.paomi.client.activity.pay.adapter.AddressListAdapter;
import com.paomi.client.activity.pay.adapter.FlowAdapter;
import com.paomi.client.activity.pay.adapter.PayPurchaserAdapter;
import com.paomi.client.activity.pay.adapter.ShopsListAdapter;
import com.paomi.client.activity.pay.model.AddressBean;
import com.paomi.client.activity.pay.model.SendMoneyBean;
import com.paomi.client.activity.person.model.CardJsonBean;
import com.paomi.client.activity.person.model.TicketBalanceBean;
import com.paomi.client.activity.takeTicket.TakeTicketActivity;
import com.paomi.client.activity.takeTicket.TakeTicketListActivity;
import com.paomi.client.activity.takeTicket.model.TakeTicketBean;
import com.paomi.client.activity.takeTicket.model.TicketPersonBean;
import com.paomi.client.activity.vip.model.CouponBean;
import com.paomi.client.base.BaseMvpActivity;
import com.paomi.client.bean.AddressInfo;
import com.paomi.client.fragment.first.model.TicketJson;
import com.paomi.client.utils.InputMethodUtils;
import com.paomi.client.utils.RxRegUtils;
import com.paomi.client.utils.ToastUtil;
import com.paomi.client.utils.UIUtils;
import com.paomi.client.utils.Util;
import com.paomi.client.view.FlowLayoutManager;
import com.paomi.client.view.SpaceItemDecoration;
import com.paomi.client.widget.RxToast;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import butterknife.BindView;
import butterknife.OnClick;

public class PayActivity extends BaseMvpActivity<PayMvpView, PayPresenter> implements PayMvpView {

    @BindView(R.id.ll_head)
    LinearLayout ll_head;
    @BindView(R.id.add_address)
    TextView addAddress;//添加新地址的按钮
    @BindView(R.id.next_btn)
    TextView next_btn;
    @BindView(R.id.line_tv)
    TextView line_tv;//添加新地址的按钮
    @BindView(R.id.address_list)
    RecyclerView addressList;//显示默认的列表
    @BindView(R.id.shops_list)
    RecyclerView shopsList;//显示需要买的商品
    @BindView(R.id.next_bar)
    TextView nextBar;
    @BindView(R.id.card_ll)
    LinearLayout card_ll;//卡券的点击
    @BindView(R.id.convert_check)
    CheckBox convertCheck;//抵用积分的选择
    @BindView(R.id.total_tv)
    TextView totalTv;//票价总额的显示
    @BindView(R.id.coupon_tv)
    TextView couponTv;//卡券抵扣的显示
    @BindView(R.id.belly_tv)
    TextView bellyTv;//积分抵扣的显示
    @BindView(R.id.express_tv)
    TextView expressTv;//快递费的显示
    @BindView(R.id.pay_tv)
    TextView payTv;//实付金额的显示
    @BindView(R.id.sum_money)
    TextView sumMoney;//合计金额的显示
    @BindView(R.id.btn_pay)
    Button btnPay;//立即支付的点击
    @BindView(R.id.send_type)
    LinearLayout send_type;
    @BindView(R.id.tv_show_msg)
    TextView tv_show_msg;
    @BindView(R.id.tv_convert)
    TextView tv_convert;
    private List<TicketJson> ticketJsons = new ArrayList<>();//剧目列表数据
    private ShopsListAdapter shopsListAdapter;//商品列表的适配
    private AddressListAdapter addressListAdapter;//地址列表的适配
    private List<AddressInfo> stringList = new ArrayList<>();//地址的数据
    private DetailTicketBean.TicketBean ticketBean;//演出信息
    private PlanBean planBean;//选中的场次信息
    private List<PraiseSeatBean.PraiseSeatJson> checkSeat;//选择价格以及座位信息
    private String checkJson;//选中票的json数据
    Map<String, String> map;//解析剧目显示数据
    private float totalPrice = 0;//票价总额
    private float cardPrice = 0;//卡券抵扣
    private float pointsPrice = 0;//积分抵扣
    private float sendPrice = 0;//快递费
    private List<EnterTypeBean> enterTypeList = new ArrayList<>();//入场方式（配送方式）
    private TakeTicketBean ticketTakeBean = new TakeTicketBean();//现场取票人信息
    private EnterTypeBean enterTypeBean;//入场方式（配送方式）的信息
    private int sunNum;//票的总张数
    private String cardId = "";
    private String integralNum = "";//积分抵扣的赋值
    private String integralNum_have = "";//积分抵扣的计算值
    private List<SeatBean> seatBeanList = null;//在线选座数据
    SendMoneyBean expressBean;//快递相关全部
    //购票人相关
    @BindView(R.id.tv_add_p)
    TextView tv_add_p;
    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;
    PayPurchaserAdapter adapter;
    @BindView(R.id.rec_people)
    RecyclerView rec_people;
    List<TakeTicketBean> chooseData = new ArrayList<>();//选中的购票人
    List<TakeTicketBean> personData = new ArrayList<>();//所有购票人
    @BindView(R.id.ll_buy_person)
    LinearLayout ll_buy_person;
    //取票人相关
    @BindView(R.id.ll_get_person)//取票人ll
            LinearLayout ll_get_person;
    @BindView(R.id.et_collection_name)//取票人名字
            EditText et_collection_name;
    @BindView(R.id.et_collection_phone)
    EditText et_collection_phone;//取票人手机号
    FlowAdapter flowAdapter;
    List<String> deliveryList = new ArrayList<>();

    @BindView(R.id.tv_card_voucher)
    TextView tv_card_voucher;
    @BindView(R.id.get_card)
    TextView get_card;//卡券的显示
    private boolean getPoints=false;//是否启用积分

    private Map<String,List<SeatBean>> groupLimitNeedVO;//在线选座的数据分组

    @NonNull
    @Override
    public PayPresenter createPresenter() {
        return new PayPresenter();
    }

    @Override
    protected String setTitle() {
        return getResources().getString(R.string.ticket_buy_sure);
    }

    @Override
    protected void showBack(TextView button_goback) {
        button_goback.setVisibility(View.VISIBLE);
        button_goback.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
        button_goback.setTextColor(getResources().getColor(R.color.main_color));
        button_goback.setText(getResources().getString(R.string.back_normal) + getResources().getString(R.string.back));
        button_goback.setTypeface(iconfont);
    }

    @NonNull
    @Override
    protected int getLayoutId() {
        return R.layout.activity_pay;
    }

    @Override
    protected void initEvent() {
        nextBar.setTypeface(iconfont);
        next_btn.setTypeface(iconfont);
        shopsList.setLayoutManager(UIUtils.getRecyclerViewManager(false, this));
        addressList.setLayoutManager(UIUtils.getRecyclerViewManager(false, this));
        ticketBean = (DetailTicketBean.TicketBean) getIntent().getSerializableExtra("detail");
        planBean = (PlanBean) getIntent().getSerializableExtra("plan");
        checkSeat = (List<PraiseSeatBean.PraiseSeatJson>) getIntent().getSerializableExtra("checkSeat");
        seatBeanList = (List<SeatBean>) getIntent().getSerializableExtra("getSeats");
        checkJson = getIntent().getStringExtra("getData");
        deliveryList = Arrays.asList(ticketBean.getGoods().getEnter_type().split(","));
        enterTypeList.clear();
        for (int i = 0; i < deliveryList.size(); i++) {
            for (int j = 0; j < ticketBean.getEnterTypes().size(); j++) {
                if (ticketBean.getEnterTypes().get(j).getDicKey().equals(deliveryList.get(i))) {
                    enterTypeList.add(ticketBean.getEnterTypes().get(j));
                }
            }
        }
        if(enterTypeList.size()>0){
            enterTypeList.get(0).setType(1);
            enterTypeBean = enterTypeList.get(0);

            String text = enterTypeBean.getValue().substring(0, enterTypeBean.getValue().lastIndexOf(" "));
            tv_show_msg.setText(text);
            //改变配送方式后快递费的显示
            if (enterTypeBean.getValue().contains("快递")) {
                ll_head.setVisibility(View.VISIBLE);
                ll_get_person.setVisibility(View.GONE);
            } else if (enterTypeBean.getValue().contains("自取")) {
                ll_head.setVisibility(View.GONE);
                ll_get_person.setVisibility(View.VISIBLE);
                sendPrice = 0;
                //显示快递费
                expressTv.setText(sendPrice + getResources().getString(R.string.money_get));
                //显示底部总额
                //float值的四舍五入
                String a=   new DecimalFormat("###,###.##").format(totalPrice - cardPrice - pointsPrice + sendPrice);
                sumMoney.setText("¥" + a);
            }
        }


        shopsListAdapter = new ShopsListAdapter(this, iconfont);
        shopsList.setAdapter(shopsListAdapter);
        adapter = new PayPurchaserAdapter(this,iconfont);//选中购票人adapter
        addressListAdapter = new AddressListAdapter(this, iconfont);
        addressList.setAdapter(addressListAdapter);
        getChooseData();
        addressListAdapter.setOnItemClickListener(new AddressListAdapter.OnItemClickListener() {
            @Override
            public void setOnItemClick(View view, int pos) {

            }

            @Override
            public void change() {
                Intent i = new Intent(PayActivity.this, ReceivingAddressActivity.class);
                startActivityForResult(i, 2008);
            }
        });
        /**
         * 是否能用积分与怎么用
         */
        getPresenter().getIntergalBalance("" + ticketBean.getGoods().getId());
        if (ticketBean != null) {//防止点击
            if (ticketBean.getGoods().isCoupon_flag()) {//判断是否可用优惠券
                get_card.setVisibility(View.INVISIBLE);
                nextBar.setVisibility(View.VISIBLE);
                card_ll.setClickable(true);
                card_ll.setEnabled(true);
                getPresenter().choiceCoupon("" + ticketBean.getGoods().getId());
            } else {
                tv_card_voucher.setText(getResources().getString(R.string.card_not_use));
                get_card.setVisibility(View.VISIBLE);
                nextBar.setVisibility(View.GONE);
                card_ll.setClickable(false);
                card_ll.setEnabled(false);
            }
        }
        convertCheck.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                /**
                 * 是否能用积分与怎么用
                 */
                if(!ticketBean.getGoods().isIs_integral()){//不可用积分
                    getPoints=false;
                    return;
                }
                if (isChecked) {//使用积分抵扣
                    getPoints=true;
                    getPresenter().getIntergalBalance("" + ticketBean.getGoods().getId());
                } else {//取消积分抵扣
                    getPoints=false;
//                    sendPrice = 0;
                    integralNum = "";
                    pointsPrice = 0;
                    //显示快递费
//                    expressTv.setText(sendPrice + getResources().getString(R.string.money_get));
                    //显示底部总额
                    String a=   new DecimalFormat("###,###.##").format(totalPrice - cardPrice - pointsPrice + sendPrice);
                    sumMoney.setText("¥" + a);
                }
            }
        });
        //请求默认地址
        getPresenter().getAddress();


        //购票人流式布局
        FlowLayoutManager manager = new FlowLayoutManager();
        rec_people.addItemDecoration(new SpaceItemDecoration(Util.dip2px(PayActivity.this, 10)));
        rec_people.setLayoutManager(manager);
        //判断是否需要实名
        if (ticketBean.getGoods().isIs_real_name()) {
            ll_buy_person.setVisibility(View.VISIBLE);
            if (ticketBean.getGoods().getReal_name_type() == 0) {//只需要一个购票人
                flowAdapter = new FlowAdapter(PayActivity.this, 1, ticketBean.getGoods().getReal_name_type());
            } else {//每张票都要一个人
                flowAdapter = new FlowAdapter(PayActivity.this, sunNum, ticketBean.getGoods().getReal_name_type());
            }
            getPresenter().getTicketPersonList(1);
            flowAdapter.OnItemClick(new FlowAdapter.OnItemClick() {
                @Override
                public void itemAddClick(TakeTicketBean des) {
                    chooseData.add(des);
                    adapter.setData(chooseData);
                }

                @Override
                public void itemDelClick(TakeTicketBean des) {
                    chooseData.remove(des);
                    adapter.setData(chooseData);
                }
            });
        } else {
            ll_buy_person.setVisibility(View.GONE);
        }

        rec_people.setAdapter(flowAdapter);
        //选中购票人
        recyclerview.setLayoutManager(new LinearLayoutManager(PayActivity.this));
        recyclerview.setAdapter(adapter);

        adapter.setOnDeleteItemClick(new PayPurchaserAdapter.OnDeleteItemClick() {
            @Override
            public void deleteItem(TakeTicketBean bean) {
                for (int i = 0; i < personData.size(); i++) {
                    if (personData.get(i).getId() == bean.getId()) {
                        personData.get(i).setSelect(false);
                    }
                }
                chooseData.remove(bean);
                adapter.notifyDataSetChanged();
                flowAdapter.notifyDataSetChanged();
            }
        });
    }

    void getChooseData() {
        ticketJsons.clear();
        if (checkSeat != null) {//非在线选座的数据组装

            //数据解析设置票面价格，张数，时间
            try {
                map = new Gson().fromJson(checkJson, new TypeToken<Map<String, String>>() {
                }.getType());
            } catch (Exception e) {
                e.printStackTrace();
            }
            //方法1：先获取keyset，然后循环取出value
            TicketJson ticketJson1 = ticketBean.getGoods();
            Set<String> keySet = map.keySet();
            Iterator<String> it = keySet.iterator();
            while (it.hasNext()) {
                for (int i = 0; i < checkSeat.size(); i++) {
                    PraiseSeatBean.PraiseSeatJson bean = checkSeat.get(i);
                    String get = it.next();
                    if (get.equals("" + bean.getId())) {
                        ticketJson1.setPayMoney(bean.getPrice());
                        ticketJson1.setPayNum(map.get(get));
                    }
                }
                ticketJsons.add(ticketJson1);
            }

            for (int i = 0; i < checkSeat.size(); i++) {
//            TicketJson ticketJson=ticketBean.getGoods();
                for (Map.Entry<String, String> entry : map.entrySet()) {
                    System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
                    sunNum += Integer.parseInt(entry.getValue());
//                ticketJson.setDate(planBean.getName());
//                ticketJson.setPayNum(entry.getValue());
//                if (entry.getKey().equals("" + checkSeat.get(i).getId())) {
//                    ticketJson.setPayMoney(checkSeat.get(i).getPrice());
//                }
//                break;
                }
//            ticketJsons.add(ticketJson);
//            break;
            }
            //显示选票信息
            shopsListAdapter.setData(ticketBean.getGoods(),ticketJsons, seatBeanList,null);
            shopsListAdapter.notifyDataSetChanged();
            //显示票价总额
            for (int i = 0; i < ticketJsons.size(); i++) {
                totalPrice += Float.parseFloat(ticketJsons.get(i).getPayMoney()) * Integer.parseInt(ticketJsons.get(i).getPayNum());
            }
        } else if (seatBeanList != null) {//在线选座的数据组装
            //统计总共多少张票
            sunNum=seatBeanList.size();
            //根据价格进行分组
            getOnlineList(seatBeanList);
            //如果需要再次对分组后的数据进行操作,可以取出对应的数据
            Set<String> keySet = groupLimitNeedVO.keySet();
            for(String groupName : keySet) {
//                System.out.println("当前分组为"+groupName);
                TicketJson ticketJson1 = new TicketJson();
                ticketJson1.setPayMoney(groupName);
                ticketJson1.setPayNum("" + groupLimitNeedVO.get(groupName).size());
//                for(SeatBean vo : groupLimitNeedVO.get(groupName)) {
//                    System.out.println(vo.getPrice());
//                }
                ticketJsons.add(ticketJson1);
            }
            //显示选票信息
            shopsListAdapter.setData(ticketBean.getGoods(),ticketJsons,seatBeanList,groupLimitNeedVO);
            shopsListAdapter.notifyDataSetChanged();
            for (SeatBean ticketItem : seatBeanList) {
                totalPrice += Float.parseFloat(ticketItem.getPrice());
            }
        }
    }

    /**
     *在线选座根据价格进行分组
     * @param stringList
     * @return
     */
    private void getOnlineList(List<SeatBean> stringList){
        List<SeatBean> getList=new ArrayList<>();
        //按照price分组,准备Map,此处使用LinkedHashMap的原因是为了保证后续遍历的时候,按照分组时的add顺序来操作
        groupLimitNeedVO = new LinkedHashMap<String,List<SeatBean>>();
        for(SeatBean vo : stringList) {
            String groupName = vo.getPrice();
            //如果Map中的key包含此时的groupName,则取出Value,直接add此实体
            if(groupLimitNeedVO.containsKey(groupName)) {
                groupLimitNeedVO.get(groupName).add(vo);
                //否则的话,新建一个key为groupName的List,并将groupName作为key,list作为value放入map
            }else {
                List<SeatBean> groupList = new LinkedList<SeatBean>();
                groupList.add(vo);
                groupLimitNeedVO.put(groupName, groupList);
            }
        }
    }

    @OnClick(R.id.tv_add_p)
    void addPeople() {
//        PayActivity.this.startActivityForResult(new Intent(PayActivity.this, TakeTicketActivity.class), 8001);
        startActivityForResult(new Intent(this, TakeTicketListActivity.class), 8001);
    }

    @OnClick(R.id.send_type)
    void chooseSend() {//选择配送方式
        getPresenter().showDialogShip(PayActivity.this, iconfont, null, enterTypeList);
    }

    @OnClick({R.id.add_address, R.id.card_ll, R.id.convert_check, R.id.btn_pay, R.id.et_collection_name, R.id.et_collection_phone})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.add_address://添加默认地址
                startActivityForResult(new Intent(PayActivity.this, ReceivingAddressActivity.class), 2008);
                break;
            case R.id.card_ll://优惠券(卡券)的选择点击
                getPresenter().showDialogCoupon(this, iconfont, "" + ticketBean.getGoods().getId(),totalPrice);
                break;
            case R.id.convert_check:
//                RxToast.info(getResources().getString(R.string.isCheck_get)+getResources().getString(R.string.pay_value));
                break;
            case R.id.btn_pay://确认订单按钮
                InputMethodUtils.hideSoftInput(this);
                if(enterTypeBean!=null){
                    if (enterTypeBean.getValue().contains("快递")){
                        if(stringList.size()==0){
                            Util.toast(PayActivity.this, "请添加收货地址");
                            return;
                        }
                    }
                }

                //判断是否需要实名
                if (ticketBean.getGoods().isIs_real_name()) {
                    if (ticketBean.getGoods().getReal_name_type() == 0) {//只需要一个购票人
                        if (chooseData.size() < 1) {
                            Util.toast(PayActivity.this, "请选择实名购票人");
                            return;
                        }
                    } else {//每张票都要一个人
                        if (chooseData.size() < sunNum) {
//                            Util.toast(PayActivity.this, "请选择实名购票人");
                            ToastUtil.getToastEmail().ToastShow(this, null, 1, R.layout.toast_view, getResources().getString(R.string.message_ticker));
                            return;
                        }
                    }
                }
                String ids = "";
                if (chooseData.size() > 0) {//判断是否选择购票人
                    for (int i = 0; i < chooseData.size(); i++) {
                        ids += chooseData.get(i).getId() + ",";
                    }
                    ids = ids.substring(0, ids.length() - 1);
                }
                //判断是否可以下单
                if(enterTypeBean!=null){
                    if (enterTypeBean.getValue().contains("快递")) {
                        if (expressBean != null) {
                            if (expressBean.returnCode.equals("9999")) {
                                Util.toast(PayActivity.this, expressBean.returnMessage);
                                return;
                            } else if (expressBean.returnCode.equals("0000")) {
                                btnPay.setBackgroundColor(getResources().getColor(R.color.main_color));
                                btnPay.setTextColor(getResources().getColor(R.color.white));
                                btnPay.getBackground().setAlpha(100);
                                getPresenter().setOrderSure(this, "" + planBean.getGoodsId(),
                                        "" + planBean.getId(), checkJson, "" + enterTypeBean.getDicKey(),
                                        "" + stringList.get(0).getId(), "" + ids,
                                        integralNum, cardId, "", "", "0");
                            }
                        }
                    } else if (enterTypeBean.getValue().contains("自取")) {
                        if (et_collection_name.getText().toString().isEmpty()) {
                            Util.toast(PayActivity.this, getResources().getString(R.string.take_input));
                            return;
                        } else if (et_collection_phone.getText().toString().isEmpty()) {
                            Util.toast(PayActivity.this, getResources().getString(R.string.take_phone));
                            return;
                        }
                        String phone = et_collection_phone.getText().toString().trim();
                        if (phone.length() < 6 || phone.length() > 12 || !RxRegUtils.isMobileExact(phone)) {
                            RxToast.info(getResources().getString(R.string.input_phoneNu_true));
                            return;
                        }
                        btnPay.setBackgroundColor(getResources().getColor(R.color.main_color));
                        btnPay.setTextColor(getResources().getColor(R.color.white));
                        btnPay.getBackground().setAlpha(100);
                        getPresenter().setOrderSure(this, "" + planBean.getGoodsId(),
                                "" + planBean.getId(), checkJson, "" + enterTypeBean.getDicKey(),
                                "",
                                "" + ids, integralNum, cardId
                                , et_collection_name.getText().toString().trim(), et_collection_phone.getText().toString().trim(), "0");
                    }
                }
                //调用下单接口
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 2008) {//添加/修改地址
            if (resultCode == 2018 && data != null) {
                stringList.clear();
                AddressInfo info = (AddressInfo) data.getSerializableExtra("getAddress");
                stringList.add(info);
                addressListAdapter.setData(stringList);
                if (stringList.size() > 0) {//回显默认地址
                    addAddress.setVisibility(View.GONE);
                    line_tv.setVisibility(View.VISIBLE);
                    addressList.setVisibility(View.VISIBLE);
                } else {
                    addAddress.setVisibility(View.VISIBLE);
                    line_tv.setVisibility(View.GONE);
                }
                //请求快递费
                getPresenter().getCalculatePass("" + ticketBean.getGoods().getId(), "" + stringList.get(0).getId(), "" + sunNum);
            }
        } else if (requestCode == 8001) {//得到现场取票的人
            if (resultCode == 2001 && data != null) {
                ticketTakeBean = (TakeTicketBean) data.getSerializableExtra("takeBean");
                if (ticketTakeBean != null) {
                    ticketTakeBean.setSelect(false);
//                    personData.add(ticketTakeBean);
//                    flowAdapter.notifyDataSetChanged();
                    getPresenter().getTicketPersonList(1);
                }

            }
        }
    }

    /**
     * 请求默认地址
     *
     * @param addressData
     */
    @Override
    public void setAddressData(AddressBean addressData) {
        if (addressData.getReturnData() != null) {
            stringList.clear();
            addAddress.setVisibility(View.GONE);
            line_tv.setVisibility(View.VISIBLE);
            addressList.setVisibility(View.VISIBLE);
            stringList.add(addressData.getReturnData());
            addressListAdapter.setData(stringList);
        } else {
            addAddress.setVisibility(View.VISIBLE);
            line_tv.setVisibility(View.GONE);
        }

        Log.e("ticketList", "" + ticketJsons.size());
        //float值的四舍五入
        String a1=   new DecimalFormat("###,###.##").format(totalPrice);
        totalTv.setText("" + a1 + getResources().getString(R.string.money_get));
        //显示卡券抵扣
        couponTv.setText("-" + cardPrice + getResources().getString(R.string.money_get));
        //显示积分抵扣
        bellyTv.setText("-" + pointsPrice + getResources().getString(R.string.money_get));
        //请求快递费
        if (stringList.size() > 0) {//有默认数据
            if(ll_head.getVisibility()==View.VISIBLE){
                getPresenter().getCalculatePass("" + ticketBean.getGoods().getId(), "" + stringList.get(0).getId(), "" + sunNum);
            }
        } else {
            addAddress.setVisibility(View.VISIBLE);
            line_tv.setVisibility(View.GONE);
        }
        //显示快递费
        expressTv.setText(sendPrice + getResources().getString(R.string.money_get));
        //显示底部总额
        String a=   new DecimalFormat("###,###.##").format(totalPrice - cardPrice - pointsPrice + sendPrice);
        sumMoney.setText("¥" + a);

    }

    /**
     * 得到优惠券的数据
     * "type": 1,//1.满减券 2.折扣券
     *
     * @param couponData
     */
    @Override
    public void setCouponData(CardJsonBean couponData) {
        if(couponData==null){//没有可选择的卡券
            cardId="";
            get_card.setVisibility(View.VISIBLE);
            get_card.setText(getResources().getString(R.string.card_null));
            nextBar.setVisibility(View.VISIBLE);
            cardPrice=0;
            //显示底部总额
            couponTv.setText("-" + cardPrice + getResources().getString(R.string.money_get));
            String a=   new DecimalFormat("###,###.##").format(totalPrice - cardPrice - pointsPrice + sendPrice);
            sumMoney.setText("¥" + a);
        }else{
            get_card.setVisibility(View.VISIBLE);
            cardId = couponData.getId() + "";
            if (couponData.getType() == 1) {//1.满减券 2.折扣券
                cardPrice = couponData.getAmount();
                couponTv.setText("-" + cardPrice + getResources().getString(R.string.money_get));
            } else if (couponData.getType() == 2) {
                //折扣券是启用金额enableAmount*打折的比例amount
                int money=couponData.getEnableAmount() * couponData.getAmount();
                cardPrice = Float.parseFloat(""+money)/100;
                couponTv.setText("-" + cardPrice + getResources().getString(R.string.money_get));
            }
            //显示底部总额
            String a=   new DecimalFormat("###,###.##").format(totalPrice - cardPrice - pointsPrice + sendPrice);
            sumMoney.setText("¥" + a);
            get_card.setText(couponData.getName());
            nextBar.setVisibility(View.VISIBLE);
        }

    }

    /**
     * 卡券默认选择
     * @param couponDataList
     */
    @Override
    public void setCouponChoice(List<CardJsonBean> couponDataList) {
        if(couponDataList==null){//没有可选择的卡券
            cardId="";
            get_card.setVisibility(View.VISIBLE);
            nextBar.setVisibility(View.VISIBLE);
        }else{
            if(couponDataList.size()>0){//有可选择的卡券
                get_card.setVisibility(View.VISIBLE);
                //默认第一张
                int num=0;//几张优惠券可用
                for(int i=0;i<couponDataList.size();i++){
                    CardJsonBean card=couponDataList.get(i);
                    if(totalPrice>=card.getEnableAmount()){
                        num++;
                    }
                }
                get_card.setText(String.format(getResources().getString(R.string.card_num_can), num));
//                if(totalPrice >= couponDataList.get(0).getEnableAmount()){
//                    get_card.setText(couponDataList.get(0).getName());
//                    get_card.setVisibility(View.VISIBLE);
//                    cardId = couponDataList.get(0).getId() + "";
//                    if (couponDataList.get(0).getType() == 1) {//1.满减券 2.折扣券
//                        cardPrice = couponDataList.get(0).getAmount();
//                        couponTv.setText("-" + cardPrice + getResources().getString(R.string.money_get));
//                    } else if (couponDataList.get(0).getType() == 2) {
//                        //折扣券是启用金额enableAmount*打折的比例amount
//                        cardPrice = couponDataList.get(0).getEnableAmount() * couponDataList.get(0).getAmount()/100;
//                        couponTv.setText("-" + cardPrice + getResources().getString(R.string.money_get));
//                    }
//                    //显示底部总额
//                    String a=   new DecimalFormat("###,###.##").format(totalPrice - cardPrice - pointsPrice + sendPrice);
//                    sumMoney.setText("¥" + a);
//                }
                nextBar.setVisibility(View.VISIBLE);
            }else{//没有可选择的卡券
                cardId="";
                get_card.setVisibility(View.VISIBLE);
                nextBar.setVisibility(View.VISIBLE);
                get_card.setText(String.format(getResources().getString(R.string.card_num_can), 0));
            }
        }
    }

    /**
     * 得到配送方式的数据
     *
     * @param enterData
     */
    @Override
    public void setEnterData(EnterTypeBean enterData) {
        enterTypeBean = enterData;
        String text = enterData.getValue().substring(0, enterData.getValue().lastIndexOf(" "));
        tv_show_msg.setText(text);
        //改变配送方式后快递费的显示
        if (enterData.getValue().contains("快递")) {
            ll_head.setVisibility(View.VISIBLE);
            ll_get_person.setVisibility(View.GONE);
            //获取快递费
            getPresenter().getCalculatePass("" + ticketBean.getGoods().getId(), "" + stringList.get(0).getId(), "" + sunNum);
        } else if (enterData.getValue().contains("自取")) {
            ll_head.setVisibility(View.GONE);
            ll_get_person.setVisibility(View.VISIBLE);
            sendPrice = 0;
            //显示快递费
            expressTv.setText(sendPrice + getResources().getString(R.string.money_get));
            //显示底部总额
            String a=   new DecimalFormat("###,###.##").format(totalPrice - cardPrice - pointsPrice + sendPrice);
            sumMoney.setText("¥" + a);
        }
    }

    /**
     * 得到积分汇算
     *
     * @param result
     */
    @Override
    public void setIntergalBanlance(TicketBalanceBean result) {
        if (result == null) {//获得数据 integralNum
//            pointsPrice = result.getReturnData();
//            integralNum =
//            pointsPrice
            return;

        }
        if (result.returnCode.equals("0000")) {
            convertCheck.setClickable(true);
            convertCheck.setEnabled(true);
            if (result.getReturnData() != null) {//判断防空
                TicketBalanceBean.TicketBalJson getBanlance = result.getReturnData().getData().get(0);
                if (getBanlance != null) {//防空
                    int max = (int) (totalPrice * getBanlance.getIntegralBalance());
                    int maxjf = (int) (max * getBanlance.getRate());
                    if (maxjf < getBanlance.getThreshold()) {
                        integralNum_have = max + "";
                        tv_convert.setText("可用" + maxjf + "积分可抵扣" + max + getResources().getString(R.string.money_get));
                    } else {
                        integralNum_have = getBanlance.getThreshold() / getBanlance.getIntegralBalance() + "";
                        tv_convert.setText("可用" + getBanlance.getThreshold() + "积分可抵扣" + integralNum_have + getResources().getString(R.string.money_get));
                    }
                }
            }else{//没有积分可用
                convertCheck.setChecked(false);
            }
            if(getPoints){//启用积分
                integralNum = integralNum_have;
                if (!("").equals(integralNum)) {
                    //显示积分抵扣金额
                    pointsPrice = Float.valueOf(integralNum);
                    //显示积分抵扣
                    bellyTv.setText("-" + pointsPrice + getResources().getString(R.string.money_get));
                    //显示底部总额
                    String a=   new DecimalFormat("###,###.##").format(totalPrice - cardPrice - pointsPrice + sendPrice);
                    sumMoney.setText("¥" + a);
                }
            }
        } else if (result.returnCode.equals("0003")) {
            tv_convert.setText(result.returnMessage);
            convertCheck.setClickable(false);
            convertCheck.setEnabled(false);
        } else {
            Util.toast(this, result.returnMessage);
            convertCheck.setClickable(false);
            convertCheck.setEnabled(false);
        }
    }

    /**
     * 得到快递费
     *
     * @param sendMoneyBean
     */
    @Override
    public void setPassMoney(SendMoneyBean sendMoneyBean) {
        expressBean = sendMoneyBean;
        if (sendMoneyBean.returnCode.equals("9999")) {
            Util.toast(this, sendMoneyBean.returnMessage);
            expressTv.setText(sendMoneyBean.returnMessage);
        } else if (sendMoneyBean.returnCode.equals("0000")) {
            sendPrice = sendMoneyBean.getReturnData();
            //显示快递费
            expressTv.setText(sendPrice + getResources().getString(R.string.money_get));
            //显示底部总额
            String a=   new DecimalFormat("###,###.##").format(totalPrice - cardPrice - pointsPrice + sendPrice);
            sumMoney.setText("¥" + a);
        }
    }


    @Override
    public void setPersonList(TicketPersonBean result) {
        personData.clear();
        personData = result.getReturnData().getData();
        //去除重复的数据
        if(personData.size()>0){
//            personData=removeDuplicate(personData);
//            flowAdapter.setData(personData);
        }
        flowAdapter.setData(personData);

    }

    /**
     * 去除重复数据
     * @param list
     * @return
     */
    private List<TakeTicketBean>  removeDuplicate(List<TakeTicketBean> list)  {
        for  ( int  i  =   0 ; i  <  list.size()  -   1 ; i ++ )  {
            for  ( int  j  =  list.size()  -   1 ; j  >  i; j -- )  {
                TakeTicketBean bean1=list.get(j);
                TakeTicketBean bean2=list.get(i);
                if  (bean1.getCode().equals(bean2.getCode())&& bean1.getName().equals(bean2.getName()))  {
                    list.remove(j);
                }
            }
        }
        return list;
    }

}
